// 阻塞队列的实现
#pragma once
#include "Mutex.hpp"
#include "Cond.hpp"
#include <iostream>
#include <string>
#include <queue>

const int defaultcap = 5;

using namespace MutexModule;
using namespace CondModule;

template <typename T>
class BlockQueue
{
private:
    bool IsFull() { return _q.size() >= _cap; }
    bool IsEmpty() { return _q.empty() };

public:
    BlockQueue(int cap = defaultcap)
        : _cap(cap),
          _csleep_num(0),
          _psleep_num(0)
    {
    }

    void Equeue(const T &in)
    {
        {
            LockGuard lockguard(_mutex);
            // 生产者调用
            while (IsFull())
            {
                // 等待了
                _psleep_num++;
                _full_cond.Wait(_mutex);
                _psleep_num--;
            }
            // 暂定
            _q.push(in);

            // 临时方案
            if (_csleep_num > 0)
            {
                _empty_cond.Signal();
                std::cout << "唤醒消费者..." << std::endl;
            }
        }
    }

    T Pop()
    {
        // 消费者调用
        T data;
        {
            LockGuard lockguard(_mutex);
            while (IsEmpty())
            {
                _csleep_num++;
                _empty_cond.Wait(_mutex);
                _csleep_num--;
            }
            data = _q.front();
            _q.pop();
            if (_psleep_num > 0)
            {
                _full_cond.Signal();
                std::cout << "唤醒生产者..." << std::endl;
            }
        }
        return data;
    }

    ~BlockQueue()
    {
    }

private:
    std::queue<T> _q; // 临界资源
    int _cap;         // 容量大小
    Mutex _lock;
    Cond _full_cond;
    Cond _empty_cond;

    int _csleep_num; // 消费者休眠个数
    int _psleep_num; // 生产者休眠个数
};